import time
import hmac
from requests import Request
from quant.exchanges import util








def get_ts():
    return int(1000*time.time())


def sign(message, secret_key):
    mac = hmac.new(secret_key.encode(), message.encode(), digestmod='sha256')
    sign = mac.hexdigest()
    return sign


def build_request(host, method, path, api_key, secret_key, param=None):
    if param is None:
        param = {}

    param['timestamp'] = get_ts()
    parsed = util.parse_params(param)
    sig = sign(parsed, secret_key)

    url = f'{host}/{path}?{parsed}&signature={sig}'
    header = {'X-MBX-APIKEY': api_key}

    req = Request(method, url, header)
    return req


def sign_ws_param(params, api_key, secret_key):
    params['timestamp'] = get_ts()
    params['apiKey'] = api_key
    parsed = util.parse_params_sorted(params)
    sig = sign(parsed, secret_key)
    params['signature'] = sig
    return params













